<?php
/*
 * @Author       : ZengHao
 * @Date         : 2023-12-26 08:54:01
 * @LastEditors  : ZengHao
 * @LastEditTime : 2024-02-25 18:36:38
 * @FilePath     : /inc/options/options.php
 * @Description  : 
 * Copyright 2023 www.exehub.net, All Rights Reserved. 
 * 2023-12-26 08:54:01
 */

//载入文件
$options = array(
    'options-module',
    'admin-options',
    'profile-options',
    'metabox-options',
    'action'
);

foreach ($options as $option) {
    $path = 'inc/options/' . $option . '.php';
    require get_theme_file_path($path);
}

function el_new_badge()
{
    return array(
        '1.0' => '<badge style="background: #ff876b;">V1.0</badge>',
        '1.1' => '<badge style="background: #ff876b;">V1.1</badge>',
        '1.2' => '<badge>NEW</badge>',
        '1.3' => '<badge>NEW</badge>',
        '1.4' => '<badge>NEW</badge>',
        '1.5' => '<badge>NEW</badge>',
    );
}

// 后台文件加载
if (is_admin()) {
    //自定义css、js
    function el_cfs_enqueue()
    {
        // Style
        wp_enqueue_style('csf_custom_css', EL_ASSETS . 'css/options.min.css', array(), EL_VERSION);
        // Script
        wp_enqueue_script('csf_custom_js', EL_ASSETS . 'js/options.min.js', array('jquery'), EL_VERSION);
    }
    add_action('csf_enqueue', 'el_cfs_enqueue');

    //使用Font Awesome 4
    add_filter('csf_fa4', '__return_true');
}

//伪静态检测通知
function el_notice_permalink_structure()
{
    if (!get_option('permalink_structure')) {
        $con = '<div class="notice notice-error is-dismissible">
            <h2 style="color:#f73d3f;"><i class="dashicons-before dashicons-admin-settings"></i> 请完成固定链接设置</h2>
            <p>您的网站还未完成固定链接配置，部分页面会出现404错误，请先完成伪静态和固定链接设置</p>
            <p><a class="button button-primary" style="margin: 2px;" href="' . admin_url('options-permalink.php') . '">立即设置</a><a target="_blank" class="button" style="margin: 2px;" href="https://www.exehub.net">查看官网教程</a></p>
        </div>';
        echo $con;
    }
}
add_action('admin_notices', 'el_notice_permalink_structure');

//主题首次新安装通知
function el_notice_new_install()
{
    $version = get_option('el_version');
    if (!$version) {
        $theme_version = wp_get_theme()['Version'];
        do_action('el_new_install_notices', $theme_version);

        $con = '<div class="notice notice-success is-dismissible">
				<h2 style="color:#fd4c73;"><i class="fa fa-heart fa-fw"></i> 感谢您使用子比主题</h2>
                <p>使用elll子比主题请务必先配置好伪静态和固定链接，否则会出现404错误！<a target="_bank" style="color:#217ff9;" href="https://www.elll.com/3025.html">查看官网教程</a></p>
			</div>';
        echo $con;
    }
}
add_action('admin_notices', 'el_notice_new_install');

//保存主题时候保存必要的wp设置
function el_save_wp_options()
{
    update_option('default_comments_page', 'oldest');
    update_option('comment_order', 'asc');

    $theme_data = wp_get_theme();
    update_option('el_version', $theme_data['Version']);

    /**
     * 刷新固定连接
     */
    flush_rewrite_rules();
}
add_action("csf_el_options_saved", 'el_save_wp_options');

// 检测是否有更新
function el_has_update()
{
    $new_version = json_decode(el_get_ThemeVersion(false));
    if ($new_version->error == 0) {
        return true;
    } else {
        return false;
    }

}

// 获取更新版本
add_action('wp_ajax_el_get_ThemeVersion', 'el_get_ThemeVersion');
function el_get_ThemeVersion($echo = true)
{
    $set = array();
    $theme_data = wp_get_theme();
    // $is_skip_update = get_option('is_skip_update');
    // if ($is_skip_update == '1') {
    //     if ($echo) {
    //         echo el_res(1, "你已经跳过本次更新！", null);
    //         exit();
    //     } else {
    //         return el_res(1, "你已经跳过本次更新！", null);
    //     }
    // }
    // 更新地址，TODO:做成version.php 加参数进行更新，如果域名不在授权列表，直接去掉更新
    $url = 'https://www.exehub.net/eleven/info.json';
    $request = new WP_Http;
    $result = $request->request($url);
    if (!is_wp_error($result)) {
        $json = json_decode($result['body'], true);
        if (isset($json)) {
            $set['theme_info']['slug'] = $json['slug'];
            $set['theme_info']['version'] = $json['version'];
            $set['theme_info']['download_url'] = $json['download_url'];
            $set['theme_info']['current_version'] = $theme_data['Version']; //当前的主题版本
            $set['theme_info']['update_time'] = $json['update_time'];
            update_option('el_update_info', json_encode($set));
            if (strcmp($json['version'], $theme_data['Version']) == 0) {
                update_option('is_skip_update', '1');
                update_option('theme_is_update', '0');
                update_option('theme_next_check_time', time() - NEXT_WEAK);
                if ($echo) {
                    echo el_res(1, "当前已是最新版本，无需进行更新!", null);
                    exit();
                } else {
                    return el_res(1, "当前已是最新版本，无需进行更新!", null);
                }
            } else {
                update_option('is_skip_update', '0');
                update_option('theme_is_update', '1');
                update_option('theme_next_check_time','0');
                if ($echo) {
                    echo el_res(0, "获取成功，最新版本：" . $json['version'] . "，更新时间：" . $json['update_time'], array(
                        'name' => $json['name'],
                        'slug' => $json['slug'],
                        'version' => $json['version'],
                        'download_url' => $json['download_url'],
                        'details_url' => $json['details_url'],
                        'update_title' => $json['update_title'],
                        'update_content' => $json['update_content'],
                        'update_time' => $json['update_time'],
                    ));
                    exit();
                } else {
                    return el_res(0, "获取成功，最新版本：" . $json['version'] . "，更新时间：" . $json['update_time'], array(
                        'name' => $json['name'],
                        'slug' => $json['slug'],
                        'version' => $json['version'],
                        'download_url' => $json['download_url'],
                        'details_url' => $json['details_url'],
                        'update_title' => $json['update_title'],
                        'update_content' => $json['update_content'],
                        'update_time' => $json['update_time'],
                    ));
                }

            }
        } else {
            if ($echo) {
                echo el_res(1, "获取失败，请手工更新！!", null);
                exit();
            } else {
                return el_res(1, "获取失败，请手工更新！!", null);
            }
        }
    } else {
        if ($echo) {
            echo el_res(1, "获取失败，请手工更新！!", null);
            exit();
        } else {
            return el_res(1, "获取失败，请手工更新！!", null);
        }
    }
}


// 更新动作
add_action('wp_ajax_el_update', 'el_update');
function el_update()
{
    $el_update_info = get_option('el_update_info');
    $download_url = json_decode($el_update_info)->theme_info->download_url;
    $theme_info = json_decode($el_update_info)->theme_info;
    $dir = get_template_directory() . '/tmp';
    if (!is_dir($dir)) {
        mkdir($dir);
    }
    $filename = time() . '.zip';
    $theme_dir = $dir . "/{$filename}";
    $result = el_download_url($download_url, $theme_dir);
    $zip = new ZipArchive();
    if ($zip->open($theme_dir) === true && $result) {
        $zip->extractTo(get_theme_root() . '/tmp');
        $zip->close();
        el_del_dir($dir);
        update_option('is_skip_update', '1');
        update_option('theme_is_update', '0');
        echo el_res(0, "更新成功!", null);
        exit();
    } else {
        echo el_res(1, "解压失败!", array(
            'el_update_info' => $el_update_info,
            'download_url' => $download_url,
            'theme_info' => $theme_info,
            'result' => $result,
        ));
        exit();
    }
}

// 下载更新包
function el_download_url($url, $filepath)
{
    $tmp_file = download_url($url);

    try {
        // 将文件复制到最终目标并删除临时文件。
        $result = copy($tmp_file, $filepath);
        @unlink($tmp_file);
    } catch (\Exception $e) {
        echo el_res(1, "下载失败!", $e->getMessage());
        exit();
    }
    return $result;
}

//循环加上递归 删除文件
function el_del_dir($dir)
{
    // 判断给定文件名是否是一个目录
    if (is_dir($dir)) {
        //获取目录数组，如果用fopen 然后在fread什么的麻烦
        $files = scandir($dir);
        //获取到单个的文件 但是这里的话路径不一定是正确的
        foreach ($files as $file) {
            //把. 和.. 去掉
            if ($file == '.' || $file == '..') {
                continue;
            } else {
                //此时就得获取到正确的路径下的文件或者目录
                $path = $dir . '/' . $file;
                //此时判断一下文件的类型是文件还是目录，是文件直接干掉
                if (is_dir($path)) {
                    //如果是目录的话，直接递归
                    deldir($path);
                } else {
                    //如果是文件的话直接删除
                    unlink($path);
                }
            }
        }
        //如果都清除干净了，直接删除空目录
        rmdir($dir);
    }
}

add_action('admin_head', 'el_admin_add_term_img_init');
function el_admin_add_term_img_init()
{
    $z_taxonomies = get_taxonomies();
    if (is_array($z_taxonomies)) {
        foreach ($z_taxonomies as $z_taxonomy) {
            if ('link_category' == $z_taxonomy) {
                continue;
            }

            add_filter($z_taxonomy . '_row_actions', 'el_filter_row_actions', 1, 2);

            if ('plate_cat' == $z_taxonomy) {
                continue;
            }

            add_action($z_taxonomy . '_add_form_fields', 'el_admin_add_term_img_form_field');
            add_action($z_taxonomy . '_edit_form_fields', 'el_admin_add_term_img_form_field_edit');
            add_filter('manage_edit-' . $z_taxonomy . '_columns', 'el_admin_add_term_img_edit_columns');
            add_filter('manage_' . $z_taxonomy . '_custom_column', 'el_admin_add_term_img_custom_column', 10, 3);
        }
    }
}

function el_filter_row_actions($row_actions, $term)
{
    return array_merge($row_actions, ['term_id' => 'ID：' . $term->term_id]);
}
// 添加分类时候的添加图像
function el_admin_add_term_img_form_field()
{
    if (get_bloginfo('version') >= 3.5) {
        wp_enqueue_media();
    } else {
        wp_enqueue_style('thickbox');
        wp_enqueue_script('thickbox');
    }
    echo '<div class="form-field">
		<label for="taxonomy_image">' . __('封面图像', 'zci') . '</label>
		<input type="text" name="taxonomy_image" id="taxonomy_image" value="" />
        <br/>
        <p>设置封面图，建议尺寸为1000x400,如果分类页未开启侧边栏，请选择更大的尺寸，需要在主题设置-分类、标签页：开启分类、标签封面显示功能</p>
		<button class="z_upload_image_button button">' . __('上传/添加图像', 'zci') . '</button>
	</div>' . z_edit_texonomy_script();
}

// 编辑分类时候的添加图像
define('E_IMAGE_PLACEHOLDER', EL_ASSETS . 'img/thumbnail-lg.svg');
// 上传按钮的js函数
function z_edit_texonomy_script()
{
    return '<script type="text/javascript">
    (function ($, window, document) {
	    jQuery(document).ready(function($) {
			var wordpress_ver = "' . get_bloginfo("version") . '", upload_button;
			$(".z_upload_image_button").click(function(event) {
				upload_button = $(this);
				var frame;
				if (wordpress_ver >= "3.5") {
					event.preventDefault();
					if (frame) {
						frame.open();
						return;
					}
					frame = wp.media();
					frame.on( "select", function() {
						// Grab the selected attachment.
						var attachment = frame.state().get("selection").first();
						frame.close();
						if (upload_button.parent().prev().children().hasClass("tax_list")) {
							upload_button.parent().prev().children().val(attachment.attributes.url);
							upload_button.parent().prev().prev().children().attr("src", attachment.attributes.url);
						}
						else
                            $("#taxonomy_image").val(attachment.attributes.url);
                            upload_button.parent().find(".taxonomy-image").attr("src", attachment.attributes.url);
					});
					frame.open();
				}
				else {
					tb_show("", "media-upload.php?type=image&amp;TB_iframe=true");
					return false;
				}
			});

			$(".z_remove_image_button").click(function() {
				$("#taxonomy_image").val("");
                $(this).parent().siblings(".title").children("img").attr("src","' . E_IMAGE_PLACEHOLDER . '");
                $(this).parent().find(".taxonomy-image").attr("src", "' . E_IMAGE_PLACEHOLDER . '");

				$(".inline-edit-col :input[name=\'taxonomy_image\']").val("");
				return false;
			});

			if (wordpress_ver < "3.5") {
				window.send_to_editor = function(html) {
					imgurl = $("img",html).attr("src");
					if (upload_button.parent().prev().children().hasClass("tax_list")) {
						upload_button.parent().prev().children().val(imgurl);
						upload_button.parent().prev().prev().children().attr("src", imgurl);
					}
					else
						$("#taxonomy_image").val(imgurl);
					tb_remove();
				}
			}

			$(".editinline").on("click", function(){
			    var tax_id = $(this).parents("tr").attr("id").substr(4);
			    var thumb = $("#tag-"+tax_id+" .thumb img").attr("src");
				if (thumb != "' . E_IMAGE_PLACEHOLDER . '") {
					$(".inline-edit-col :input[name=\'taxonomy_image\']").val(thumb);
				} else {
					$(".inline-edit-col :input[name=\'taxonomy_image\']").val("");
				}
				$(".inline-edit-col .title img").attr("src",thumb);
			});
	    });
    })(jQuery, window, document);
	</script>';
}
function el_admin_add_term_img_form_field_edit($taxonomy)
{
    if (get_bloginfo('version') >= 3.5) {
        wp_enqueue_media();
    } else {
        wp_enqueue_style('thickbox');
        wp_enqueue_script('thickbox');
    }
    $image_text = el_get_taxonomy_img_url($taxonomy->term_id, null);
    echo '<tr class="form-field">
		<th scope="row" valign="top"><label for="taxonomy_image">' . __('图像', 'zci') . '</label></th>
		<td><img class="taxonomy-image" src="' . $image_text . '"/><br/><input type="text" name="taxonomy_image" id="taxonomy_image" value="' . $image_text . '" /><br />
        <p>设置封面图，建议尺寸为1000x400,如果分类页未开启侧边栏，请选择更大的尺寸，需要在主题设置-分类、标签页：开启分类、标签封面显示功能</p>
        <button class="z_upload_image_button button">' . __('上传/添加图像', 'zci') . '</button>
		<button class="z_remove_image_button button">' . __('删除图像', 'zci') . '</button>
		</td>
	</tr>' . z_edit_texonomy_script();
}

// 保存函数
add_action('edit_term', 'el_admin_save_term_img');
add_action('create_term', 'el_admin_save_term_img');
function el_admin_save_term_img($term_id)
{
    if (isset($_POST['taxonomy_image'])) {
        update_option('_taxonomy_image_' . $term_id, $_POST['taxonomy_image']);
        wp_cache_delete($term_id, 'taxonomy_image_');
        wp_cache_delete($term_id, 'taxonomy_image_full');
        wp_cache_delete($term_id, 'taxonomy_image_thumbnail');
        wp_cache_delete($term_id, 'taxonomy_image_medium');
        wp_cache_delete($term_id, 'taxonomy_image_large');
    }
}

function el_admin_add_term_img_quick_edit_custom_box($column_name, $screen, $name)
{
    if ('thumb' == $column_name) {
        echo '<fieldset>
		<div class="thumb inline-edit-col">
			<label>
				<span class="title"><img src="" alt="Thumbnail"/></span>
				<span class="input-text-wrap"><input type="text" name="taxonomy_image" value="" class="tax_list" /></span>
                <span class="input-text-wrap">
                <p>设置封面图，建议尺寸为1000x400,如果分类页未开启侧边栏，请选择更大的尺寸，需要在主题设置-分类、标签页：开启分类、标签封面显示功能</p>
					<button class="z_upload_image_button button">' . __('上传/添加图像', 'zci') . '</button>
					<button class="z_remove_image_button button">' . __('删除图像', 'zci') . '</button>
				</span>
			</label>
		</div>
	</fieldset>';
    }

}

function el_admin_add_term_img_edit_columns($columns)
{
    $new_columns          = array();
    $new_columns['thumb'] = __('图像', 'zci');
    return array_merge($new_columns, $columns);
}

function el_admin_add_term_img_custom_column($columns, $column, $id)
{
    if ('thumb' == $column) {
        $columns = '<span><img src="' . el_get_taxonomy_img_url($id, null, E_IMAGE_PLACEHOLDER) . '" alt="' . __('Thumbnail', 'zci') . '" class="wp-post-image" /></span>';
    }

    return $columns;
}

// change 'insert into post' to 'use this image'
function el_admin_add_term_img_change_insert_button_text($safe_text, $text)
{
    return str_replace("Insert into Post", "Use this image", $text);
}

// style the image in category list
add_action('admin_head', 'el_admin_add_term_img_add_style');

if (strpos($_SERVER['SCRIPT_NAME'], 'edit-tags.php')) {
    add_action('quick_edit_custom_box', 'el_admin_add_term_img_quick_edit_custom_box', 10, 3);
    add_filter("attribute_escape", "el_admin_add_term_img_change_insert_button_text", 10, 2);
}
function el_admin_add_term_img_add_style()
{
    echo '<style type="text/css" media="screen">
		th.column-thumb {width:60px;}
		.form-field img.taxonomy-image,.taxonomy-image{width:95%;max-width:500px;max-height:300px;}
		.inline-edit-row fieldset .thumb label span.title {display:inline-block;}
		.column-thumb span {display:inline-block;}
		.inline-edit-row fieldset .thumb img,.column-thumb img {width:55px;height:28px;}
	</style>';
}

function my_custom_icons($icons)
{
    $icons[] = array(
        'title' => '主题内置SVG图标',
        'icons' => array(
            'elsvg-like',
            'elsvg-view',
            'elsvg-comment',
            'elsvg-time',
            'elsvg-search',
            'elsvg-money',
            'elsvg-right',
            'elsvg-left',
            'elsvg-reply',
            'elsvg-circle',
            'elsvg-close',
            'elsvg-add',
            'elsvg-add-ring',
            'elsvg-post',
            'elsvg-posts',
            'elsvg-huo',
            'elsvg-favorite',
            'elsvg-menu',
            'elsvg-d-qq',
            'elsvg-d-weibo',
            'elsvg-d-wechat',
            'elsvg-d-email',
            'elsvg-user',
            'elsvg-theme',
            'elsvg-signout',
            'elsvg-set',
            'elsvg-signup',
            'elsvg-user_rp',
            'elsvg-pan_baidu',
            'elsvg-lanzou',
            'elsvg-onedrive',
            'elsvg-tianyi',
            'elsvg-menu_2',
            'elsvg-alipay',
            'elsvg-baidu',
            'elsvg-dingtalk',
            'elsvg-huawei',
            'elsvg-xiaomi',
            'elsvg-gitee',
            'elsvg-comment-fill',
            'elsvg-private',
            'elsvg-hot-fill',
            'elsvg-hot',
            'elsvg-topping',
            'elsvg-topic',
            'elsvg-plate-fill',
            'elsvg-extra-points',
            'elsvg-deduct-points',
            'elsvg-points',
            'elsvg-tags',
            'elsvg-user-auth',
            'elsvg-vip_1',
            'elsvg-vip_2',
            'elsvg-qzone-color',
            'elsvg-qq-color',
            'elsvg-weibo-color',
            'elsvg-poster-color',
            'elsvg-copy-color',
            'elsvg-user-color',
            'elsvg-user-color-2',
            'elsvg-add-color',
            'elsvg-home-color',
            'elsvg-money-color',
            'elsvg-order-color',
            'elsvg-gift-color',
            'elsvg-security-color',
            'elsvg-trend-color',
            'elsvg-msg-color',
            'elsvg-tag-color',
            'elsvg-comment-color',
            'elsvg-wallet-color',
            'elsvg-money-color-2',
            'elsvg-merchant-color',
            'elsvg-medal-color',
            'elsvg-points-color',
            'elsvg-book-color',
            'elsvg-ontop-color',
        ),
    );

    $icons = array_reverse($icons);
    return $icons;
}
add_filter('csf_field_icon_add_icons', 'my_custom_icons');